package shoozhoo.libandrotranslation;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TranslationEditActivity extends Activity {
	public static final String INTENT_EXTRA_STRING_RES = "INTENT_EXTRA_STRING_RES";
	public static final String INTENT_EXTRA_LANG = "INTENT_EXTRA_LANG";
	private static final int REQUEST_VOICE_RECOGNITION = 100;
	private EditText defEditText;
	private EditText userEditText;
	private StringRes res;
	private String toLang;
	private boolean voiceRecognition;
	private ProgressDialog dialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.libandrotranslation_edit);

		Intent intent = getIntent();

		this.res = intent.getParcelableExtra(INTENT_EXTRA_STRING_RES);

		this.defEditText = (EditText)findViewById(R.id.def_string);
		this.defEditText.setText(res.getDefString());

		TextView resTv = (TextView)findViewById(R.id.res_name);
		resTv.setText(res.getResourceName());

		this.userEditText = (EditText)findViewById(R.id.user_string);
		this.userEditText.setText(res.getUserString());
		this.userEditText.requestFocus();
		if(res.getDefString().indexOf('\n')>0){
			this.userEditText.setSingleLine(false);
		}else{
			this.userEditText.setSingleLine(true);
		}


		Button okBtn = (Button)findViewById(R.id.ok_button);
		okBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				res.setUserString(userEditText.getText().toString());
				Intent i = new Intent();
				i.putExtra(INTENT_EXTRA_STRING_RES, res);
				setResult(RESULT_OK, i);
				finish();
			}
		});

		Button cancelBtn = (Button)findViewById(R.id.cancel_button);
		cancelBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});


		this.toLang = intent.getStringExtra(INTENT_EXTRA_LANG);
		PackageManager pm = getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(
				new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if(activities.size() != 0){
			this.voiceRecognition = true;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}
	/*
	 * Menu
	 */
	private static final int MENU_GOOGLE_TRANSLATION = Menu.FIRST + 1;
	private static final int MENU_VOICE_RECOGNITION = MENU_GOOGLE_TRANSLATION + 1;
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		menu.add(0, MENU_GOOGLE_TRANSLATION, 1, R.string.zzlibandrotranslation_edit_menu_google_translation).setIcon(R.drawable.libandrotranslation_ic_menu_translation);
		if(this.voiceRecognition){
			menu.add(0, MENU_VOICE_RECOGNITION, 2, R.string.zzlibandrotranslation_edit_menu_voice_recognition).setIcon(R.drawable.libandrotranslation_ic_menu_voice);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_GOOGLE_TRANSLATION:
			this.googleTranslation();
			break;
		case MENU_VOICE_RECOGNITION:
			this.voiceRecognition();
			break;
		}
		return true;
	}

	private void googleTranslation(){
		String src = null;
		if(defEditText.isSelected()){
			src = defEditText.getText().subSequence(defEditText.getSelectionStart(), defEditText.getSelectionEnd()).toString();
		}else{
			src = defEditText.getText().toString();
		}
		if(this.dialog!=null){
			this.dialog.dismiss();
			this.dialog = null;
		}
		GoogleLanguageClient googleLang = new GoogleLanguageClient(toLang) {
			@Override
			public void onExecute(String translation, int status, String details) {
				LibAndTransUtil.log(translation+" / "+status+" / "+details);
				if(dialog!=null){
					dialog.dismiss();
					dialog=null;
				}
				if(status!=200){
					if(details==null){
						details="";
					}
					Toast.makeText(TranslationEditActivity.this, getString(R.string.zzlibandrotranslation_edit_translation_error)+details, Toast.LENGTH_LONG).show();
					return;
				}
				if(translation!=null){
					insertTranslatedText(translation);
				}
			}
		};
		googleLang.execute(src);
		this.dialog = new ProgressDialog(this);
		this.dialog.setMessage(getString(R.string.zzlibandrotranslation_edit_translating_msg));
		this.dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		this.dialog.setCancelable(false);
		this.dialog.show();
	}
	private void voiceRecognition(){
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.zzlibandrotranslation_edit_voice_recognition_msg));
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE , this.toLang);
		startActivityForResult(intent, REQUEST_VOICE_RECOGNITION);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode!=RESULT_OK){
			return;
		}
		switch (requestCode) {
		case REQUEST_VOICE_RECOGNITION:
			onVoiceRecognitionResult(data);
			break;
		default:
			break;
		}
	}

	private void onVoiceRecognitionResult(Intent data){
		ArrayList<String> matches = data.getStringArrayListExtra(
				RecognizerIntent.EXTRA_RESULTS);
		if(matches.isEmpty()){
			Toast.makeText(this, R.string.zzlibandrotranslation_edit_voice_recognition_no_recognition, Toast.LENGTH_LONG).show();
		}else if(matches.size()==1){
			insertTranslatedText(matches.get(0));
		}else{
			final CharSequence[] items = new CharSequence[matches.size()];
			for(int i=0; i<items.length; i++){
				items[i] = matches.get(i);
			}
			new AlertDialog.Builder(this)
			.setItems(items, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					CharSequence s = items[which];
					insertTranslatedText(s.toString());
				}
			})
			.create().show();
		}
	}

	private void insertTranslatedText(String s){
		userEditText.getText().insert(userEditText.getSelectionStart(), s);
	}
}
